# encoding: utf-8
require 'sinatra'
require 'socket'
# ruby --encoding=utf-8 Index.rb

configure do
  ip= IPSocket.getaddress(Socket.gethostname)
  isserver=true
  puts ip.to_s
  if ip.to_s.include?("192.168.1")
    set :bind=>"192.168.1.111"
    isserver=false
  end

  if ip.to_s.include?("127")
    set :bind=>ip.to_s
    isserver=false
  end


  if ip.to_s.include?("fe80::48e0")
      set :bind=>"192.168.2.101"
      isserver=false
  end

  if isserver
    set :bind=>"112.124.60.115"
  end
end


# enable :sessions
use Rack::Session::Pool, :expire_after => 2592000
require File.expand_path('core/Controller', File.dirname(__FILE__))
get '/do/:c/:m' do
# content_type :js

# headers 'Content-Type' =>   "text/javascript;charset=utf-8"
  headers 'Content-Type' =>   "application/javascript;charset=utf-8"
  load "controllers/"+params[:c]+".rb"
  control=Object.const_get(params[:c])
  file_path = File.dirname(__FILE__)

  obj=control.new(params,session,file_path)
  obj.method(params[:m]).call
  # params[:id]
  # params.to_s
end

post '/do/:c/:m' do
  headers 'Content-Type' =>   "application/javascript;charset=utf-8"
  load "controllers/"+params[:c]+".rb"
  control=Object.const_get(params[:c])
  file_path = File.dirname(__FILE__)

  obj=control.new(params,session,file_path)
  obj.method(params[:m]).call
end

post '/do/upfile/:c/:m' do
  file = params[:userfile]
  filename = file[:filename]
  tempfile = file[:tempfile]
  FileUtils.mkdir_p 'uploads/'
  File.open("uploads/#{filename}",'w'){|f| f.write tempfile.read}


  headers 'Content-Type' =>   "application/javascript;charset=utf-8"
  load "controllers/"+params[:c]+".rb"
  control=Object.const_get(params[:c])
  file_path = File.dirname(__FILE__)

  obj=control.new(params,session,filename)
  obj.method(params[:m]).call

end
# after do
#   puts response.status
#   puts response.body
# end
